/*
 * Copyright 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.windowmanagersample.embedding

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.window.core.ExperimentalWindowApi
import androidx.window.embedding.*
import com.example.windowmanagersample.R
import com.example.windowmanagersample.embedding.SplitActivityDetail.Companion.EXTRA_SELECTED_ITEM
import kotlin.concurrent.timerTask

@OptIn(ExperimentalWindowApi::class)
open class SplitActivityList : AppCompatActivity() {
    lateinit var splitController: SplitController
    val splitChangeListener = SplitStateChangeListener()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_split_activity_list_layout)
        findViewById<View>(R.id.root_split_activity_layout)
            .setBackgroundColor(Color.parseColor("#e0f7fa"))

        splitController = SplitController.getInstance()

        findViewById<View>(R.id.show_dialog).setOnClickListener {
//            val dialog = AlertDialog.Builder(this).setTitle(this@SplitActivityBase.javaClass.simpleName)
//                .setMessage("This Is Dialog").create()
//            val lp: WindowManager.LayoutParams = dialog.window!!.attributes
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
//            } else {
//                lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
//            }
//            dialog.window!!.attributes = lp
//            dialog.show()

            if (!splitChangeListener.isSplitDone) {
                val startIntent = Intent(this, DialogPrepareActivity::class.java)
                startActivity(startIntent)
            }

            startActivity(Intent(this, DialogInFragmentActivity::class.java))
        }
    }

    fun minSplitWidth(): Int {
        val dm = resources.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 600F, dm).toInt()
    }

    open fun onItemClick(view: View) {
        val text = (view as TextView).text ?: throw IllegalArgumentException()
        val startIntent = Intent(this, SplitActivityDetail::class.java)
        startIntent.putExtra(EXTRA_SELECTED_ITEM, text)
        startActivity(startIntent)
    }

    override fun onStart() {
        super.onStart()
        splitController.addSplitListener(
            this,
            ContextCompat.getMainExecutor(this),
            splitChangeListener
        )
    }

    override fun onStop() {
        super.onStop()
        splitController.removeSplitListener(
            splitChangeListener
        )
    }

    inner class SplitStateChangeListener : Consumer<List<SplitInfo>> {
        private var isFirstBack = true
        var isSplitDone: Boolean = false
            private set

        override fun accept(newSplitInfos: List<SplitInfo>) {
            if (!isFirstBack) isSplitDone = true
            isFirstBack = false
            findViewById<View>(R.id.infoButton).visibility =
                if (newSplitInfos.isEmpty()) View.VISIBLE else View.GONE
        }
    }

    private fun componentName(activityClass: Class<out Activity?>?): ComponentName {
        return ComponentName(
            packageName, if (activityClass != null) activityClass.name else "*"
        )
    }

    fun componentName(className: String?): ComponentName {
        return ComponentName(packageName, className!!)
    }
}
